<template>
  <!-- 导航栏 -->
  <van-nav-bar
    title="确认订单"
    left-text="返回"
    left-arrow
    fixed
    placeholder
    z-index="1000"
    @click-left="back"
  />
  <!-- 当没有设置地址时 可以添加地址 -->
  <van-contact-card v-if="!address" type="add" @click="AddressAdd" />
  <!-- 已经有地址的情况下 -->
  <van-contact-card v-else type="edit" :name="address.name" :tel="`${address.tel} ${address.region_text}`" @click="AddressEdit" />
  <!-- <van-contact-card type="edit" :tel="tel" :name="name" @click="onEdit" /> -->
  <!-- 商品卡片 -->
  <van-card
    title="商品名称"
    v-for="(item,key) in list"
    :num = "item.nums"
    :thumb="item.product.thumbs_text"
  >
  <!--  :num = "item.nums" 卡片的数量 -->
      <template #title>
        <div class="title">{{ item.product.name }}</div>
      </template>

      <!-- 卡片的插槽部分  -->
      <template #desc v-if="item.attrs">
        <van-tag v-for="(val,key) in item.attrs" :key="key" class="tag" type="primary">{{val.value}}</van-tag>
      </template>
      <template #desc v-else>
        <van-tag class="tag" type="danger">无规格数据</van-tag>
      </template>

      <template #tags>
        <div class="price">单价：￥{{item.price}}</div>
      </template>

      <template #price>
        <div class="price">合计：￥{{ item.total }}</div>
      </template>
  </van-card>
  <!-- 支付方式 -->
  <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true"></van-cell>
  <!-- 优惠券 -->
  <van-coupon-cell
    :coupons="CouponList"
    :chosen-coupon="CouponActive"
    @click="CouponShow = true"
  />
  <!-- 备注 -->
  <van-field
    v-model="remark"
    rows="2"
    autosize
    label="留言"
    type="订单备注"
    maxlength="120"
    placeholder="请输入留言"
    show-word-limit
  />
  <!-- 支付弹出框 -->
  <van-popup
    v-model:show="PayShow"
    position="bottom"
  >
      <!-- 选择器 -->
      <van-picker
        title="请选择支付方式"
        :columns="PayList"
        @cancel="PayShow = false"
        @confirm="PayConfirm"
      />
  </van-popup>
  <!-- 优惠券 -->
   <!-- 优惠券列表 -->
  <van-popup
    v-model:show="CouponShow"
    round
    position="bottom"
    style="height: 90%; padding-top: 4px;"
  >
  <!--  :exchange-button-disable是否禁用兑换按钮  :show-exchange-bar 是否展示兑换栏   @change="CouponSelect" 确认选择优惠劵发生的事件-->
    <van-coupon-list
      disabled-title="已使用"
      enabled-title="未使用"
      :disabled-coupons="DisCouponList"
      :coupons="CouponList"
      :chosen-coupon="CouponActive"
      :exchange-button-disabled=true
      :show-exchange-bar=false
      @change="CouponSelect"
    />
  </van-popup>
  
  <!-- 提交动作栏 -->
  <van-submit-bar :price="total" text-align="left" button-text="确认支付" @submit="submit" />
</template>

<script setup>

  const {proxy} = getCurrentInstance()

  let cartids = proxy.$route.query.cartids;
  //显示地址
  let busid = proxy.$business.value.id;
  let PayShow = ref(false);
  let PayActive = ref({
    text:'余额支付',value:'money'
  })
  let PayList = ref([
    {
      text:'余额支付',value:'money'
    },
    {
      text:'微信支付',value:'wx'
    },
    {
      text:'支付宝支付',value:'zfb'
    }
  ])
  let CouponActive = ref(-1)
  let CouponShow = ref(false)
  let CouponList = ref([])//可使用
  let DisCouponList = ref([]) //未使用
  //一种状态
  let list = ref([])
  let address = ref(null)
  let remark = ref('') //订单备注
  //定义个总数
  let CouponTotal = ref(0)
  onMounted(()=>{
    AddressInfo()
    CartIndex()
    CouponInfo()
  })
  //查询优惠券
  const CouponInfo = async ()=>{
    var result = await proxy.$POST({
        url:'/cart/coupon',
        params:{busid:busid}
    })
    if(!result) return false
    if(result.code == 0){
        //提醒到底了
        finished.value = true;
        return false
    }
    result.data.map((item)=>{
      if(item.status==0){
        DisCouponList.value.push({
          id: item.id,
          condition: '已使用',
          rate: item.coupon.rate,
          name: item.coupon.title,
          startAt: item.coupon.createtime,
          endAt: item.coupon.endtime,
          valueDesc: `${item.coupon.rate*100}`,
          unitDesc: '折',
      })
      }else{
        CouponList.value.push({
          id: item.id,
          condition: '未使用',
          rate: item.coupon.rate,
          name: item.coupon.title,
          startAt: item.coupon.createtime,
          endAt: item.coupon.endtime,
          valueDesc: `${item.coupon.rate*100}`,
          unitDesc: '折',
      })
      }
    })
  }
  //计算属性算一下总值
  const total = computed(()=>{
    var total = 0;
    list.value.map((item)=>{
      //判断是否选中
        total+=parseFloat(item.total);
    })
    CouponTotal.value = total;
    if(CouponActive.value != -1){
      var rate = CouponList.value[CouponActive.value].rate;
      // total = bcmul(total,rate,2);//相乘保留两位小数 用不了
      total = (total*rate).toFixed(2)
    }
    return parseFloat(total*100)
  })

  //点击后计算值 
  const CouponSelect = async(item)=>{
      CouponShow.value = false;
      CouponActive.value = item;
      if(item != -1){
        var Total = total.value / 100 //打完折后的数
        var price = CouponTotal.value - Total;
        var CouponPrice = parseFloat(price*100).toFixed(2)
        CouponList.value[item].value = CouponPrice
      }
  }
    //显示购物车列表
  const CartIndex = async ()=>{
      //发送同步请求
      var result = await proxy.$POST({
          url:'/cart/index',
          params:{busid:busid,cartids:cartids}
      })
      if(!result) return false
      if(result.code==0){
        proxy.$fail({
          message:result.msg,
          duration:1000,
          onClose:()=>proxy.$router.go(-1)
        })
      }
      list.value = result.data.cart
      //把sku规则转换成 字符串形势
      result.data.cart.map((item)=>item.attrs = JSON.parse(item.attrs))
      return false
  }
  //查询地址
  const AddressInfo = async ()=>{
    if(JSON.stringify(proxy.$address.value) != "{}"){
      address.value = proxy.$address.value
    }else{
      var result = await proxy.$POST({
      url:'/address/addressInfo',
      params:{busid:busid}
      })
      if(!result) return false
      if(result.code==0){
        proxy.$fail(result.msg)
        return false
      }
      address.value = result.data;
    }
    
   }
  //进入更改地址
  const AddressEdit = async ()=>{
    proxy.$router.push({path:'/address',query:{action:'select'}});

  }
  //新增地址
  const AddressAdd = async()=>{
    proxy.$router.push('/address/add')
  }
  //支付弹框
  const PayConfirm = ({selectedOptions}) => {
        PayShow.value = false;
        PayActive.value.value =  selectedOptions[0].value
        PayActive.value.text =  selectedOptions[0].text
  }; 
   //返回上一页
  const back = () => proxy.$router.go(-1)
  //提交
  const submit = async () =>{
    //提交需要的数据 busid 需要改变用户的余额
    //订单表 order  添加一条数据
    //pay表 这个得看你用啥支付
    //判断是否使用优惠券 couponid
    //收获地址表 addressid
    //购物车 cartid
    var params = {
      busid:busid,
      remark:remark.value,
      addressid:address.value.id,
      cartids:cartids,
      pay:PayActive.value.value
    }
    if(CouponActive.value != -1){
      params.couponid = CouponList.value[CouponActive.value].id
    }
    //发送请求
    var result = await proxy.$POST({
      url:'/order/add',
      params
    })
    if(result.code == 0){
      proxy.$fail(result.msg);
      return false
    }
    //成功的话有两种情况
    if(params.pay == 'money'){
      // orderid:result.date.orderid传入订单id
      proxy.$success({
        message:result.msg,
        onClose:()=>proxy.$router.push({path:result.url,query:{orderid:result.data.orderid}})
      })
    }else{
      proxy.$success({
        message:result.msg,
        onClose:()=>proxy.$router.push({path:result.url,query:{payid: result.data.id}})
      })
    }
  }
</script>

<style scoped>
  :deep(.cart) {
    display: flex;
    width: 100%;
  }
  ::v-deep .van-swipe-cell {
    width: 100%;
  }
  .delete-button {
    height: 100%;
  }
  .van-card{
    background-color:#fff;
  }

  .title{
    font-size:16px;
    font-weight: bold;
    margin-bottom:5px;
  }

  .TagGroup{
    margin-bottom:5px;
  }

  .tag{
    margin-right:5px;
  }

  .price{
    font-size:14px;
    font-weight: bold;
  }
</style>